package com.douma.controller;

import com.douma.dto.Comment;
import com.douma.dto.Shop;
import com.douma.service.ShopService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

/**
 * 抖码课堂，专注中国程序员基础内功修炼
 * 官网：douma-tech.com
 * 公众号：抖码课堂
 *
 * @作者 : 老汤
 */
@Controller
public class ShopController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    @Qualifier("ShopServiceImpl_StringJson")
    private ShopService shopService;

    @GetMapping("/shop/{id}")
    public String getProductById(Model model, @PathVariable Long id) {
        logger.info("开始查询商铺，商铺 id 为：" + id);
        // ① 拿到 html 需要的商铺动态数据
        Shop shop = shopService.findById(id);
        // ② 将商铺动态数据放到 html 中解析
        model.addAttribute("shop", shop);

        Comment comment = new Comment();
        comment.setShopId(id);
        model.addAttribute("comment", comment);

        logger.info("查询商铺结束，商铺 id 为：" + id);

        return "shop";
    }

    @PostMapping("/shop/comment")
    public String commentShop(@ModelAttribute Comment comment) {
        shopService.comment(comment);
        return "redirect:/shop/" + comment.getShopId();
    }

    // 用于处理访问新增商铺的页面
    @GetMapping("/shop/add")
    public String addShopPage(Model model) {
        Shop shop = new Shop();
        model.addAttribute("shop", shop);
        return "add_shop";
    }

    // 用于处理新增商铺的请求
    @PostMapping("/shop/add")
    public String addShop(@ModelAttribute Shop shop) {
        // 1. 保存商铺，并返回商铺的 id
        long shopId = shopService.addShop(shop);
        // 2. 查询新增商铺的详细信息
        return "redirect:/shop/" + shopId;
    }
}